import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: qian
 * Date: 2022-07-19
 * Time: 16:56
 */
public class HashBuck {
    static class Node{
        public int key;
        public int val;
        public Node next;
        public Node(int key,int val){
            this.key=key;
            this.val=val;
        }
    }
    public Node[] array;
    public int usedSize;
    public HashBuck(){
        array=new Node[8];
    }
    private static final double DEFAULT_LOAD_FACTOR= 0.75;
    /**
     * 存放元素
     * @param key
     * @param val
     */
    public void put(int key,int val){
        Node node=new Node(key,val);
        int index=key%array.length;
        Node cur=array[index];
        //查看是否有相同key的节点
        while (cur!=null){
            if(cur.key==key){
                cur.val=val;
                return;
            }
            cur=cur.next;
        }
        node.next=array[index];
        array[index]=node;
        usedSize++;
        if(loadFactor()>=DEFAULT_LOAD_FACTOR){
            //扩容
            resize();
        }
    }
    //扩容
    public void resize(){
        Node[] tmp=new Node[2*this.array.length];
        //再次哈希
        for(int i=0;i<array.length;i++){
            Node cur=array[i];
            while (cur!=null){
                Node curNext=cur.next;
                int index=cur.key%tmp.length;
                cur.next=tmp[index];
                tmp[index]=cur;
                cur=curNext;
            }
        }
        array=tmp;
    }
    //计算负载因子
    public double loadFactor(){
        return this.usedSize*1.0/this.array.length;
    }
    /**
     * 通过key获取val
     * @param key
     */
    public int get(int key){
        int index=key%this.array.length;
        Node cur=array[index];
        while (cur!=null){
            if(cur.key==key){
                return cur.val;
            }
            cur=cur.next;
        }
        return -1;
    }
}
